package xp2p.svc;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;


import net.jxta.document.Advertisement;

/**
 * The Class PublisherBase. Advertisement publisher thread, which works with
 * single PeerGroup
 * 
 * @param <T>
 *            the generic type of Advertisement
 */
public class PublisherBase<T extends Advertisement> extends BeatBase
{
	private boolean propagate;
	private Set<T> adv = new HashSet<T>();
	private Object syncRoot = new Object();

	private void doPublish()
	{
		synchronized (syncRoot)
		{

			Set<T> advs = getAdv();
			for (T ad : advs)
			{
				if (isPropagate())
				{
					getGroup().getDiscoveryService().remotePublish(ad,
							getLifetime());
				}
				try
				{
					getGroup().getDiscoveryService().publish(ad, getLifetime(),
							getLifetime());
				} catch (IOException e)
				{
					e.printStackTrace();
				}
				afterPublish(ad);
			}
			
		}
	}
	
	protected void  afterPublish(T ad)
	{ }

	public boolean isPropagate()
	{
		return propagate;
	}

	public void setPropagate(boolean propagate)
	{
		synchronized (syncRoot)
		{
			this.propagate = propagate;
		}
	}

	@Override
	protected void beat()
	{
		doPublish();
	}

	public Set<T> getAdv()
	{
		return adv;
	}

	public void setAdv(Set<T> adv)
	{
		synchronized (syncRoot)
		{
			this.adv = adv;
		}
	}
}
